package com.itheima.service.impl;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.itheima.dao.OrderDao;
import com.itheima.feign.ItemFeign;
import com.itheima.model.OrderInfo;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author：shenkunlin
 * @date： 2021/7/5 12:01
 * @Description：
 ***/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private NacosServiceDiscovery nacosServiceDiscovery;

    @Autowired
    private ItemFeign itemFeign;

    /***
     * 添加订单
     * @param orderInfo
     * @return
     */
    @Override
    public int save(OrderInfo orderInfo) throws NacosException {
        //使用OpenFeign远程调用
        int price = itemFeign.decrCount(orderInfo.getItemId(), orderInfo.getCount());
        if(price<=0){
            return price;
        }
        //设置总金额
        orderInfo.setPrice(orderInfo.getCount()*price);
        //下单
        return orderDao.save(orderInfo);
    }

    /***
     * 添加订单
     * @param orderInfo
     * @return
     */
    //@Override
    public int save_backup(OrderInfo orderInfo) throws NacosException {
        //获取服务列表
        //List<ServiceInstance> serviceInstances = nacosServiceDiscovery.getInstances("item");
        //获取第1个服务的IP、端口信息
        //ServiceInstance instance = serviceInstances.get(0);
        //String host = instance.getHost();
        //int port = instance.getPort();

        //使用Ribbon做客户端负载均衡
        //http://localhost:18081/item/1/2
        //Integer price = restTemplate.getForObject("http://localhost:18081/item/"+orderInfo.getItemId()+"/"+orderInfo.getCount(),Integer.class);
        //Integer price = restTemplate.getForObject("http://"+host+":"+port+"/item/"+orderInfo.getItemId()+"/"+orderInfo.getCount(),Integer.class);
        Integer price = restTemplate.getForObject("http://item/item/"+orderInfo.getItemId()+"/"+orderInfo.getCount(),Integer.class);
        //设置总金额
        orderInfo.setPrice(orderInfo.getCount()*price);
        //下单
        return orderDao.save(orderInfo);
    }

    /**
     * 根据ID查询订单信息
     * @param id
     * @return
     */
    @Override
    public OrderInfo one(Integer id) {
        return orderDao.one(id);
    }
}